package weizan

import (
	"encoding/json"
	"errors"
	"log"
	"server/utils/tools"
)

type RoomUser struct {
	Msg  string `json:"msg"`
	Code int    `json:"code"`
	Data struct {
		List []struct {
			Uid          string  `json:"uid"`
			UserId       int     `json:"userId"`
			Nickname     string  `json:"nickname"`
			Avatar       string  `json:"avatar"`
			Phone        string  `json:"phone"`
			Area         string  `json:"area"`
			ThirdOpenid  string  `json:"third_openid"`
			LiveDuration float64 `json:"live_duration"`
		} `json:"list"`
		Total  int    `json:"total"`
		LastId string `json:"lastId"`
	} `json:"data"`
}

// 直播间用户列表
func GetRoomUserList(param map[string]any) (RoomUser, error) {

	url := "https://openapi.vzan.com/api/v2/topic/get_live_user_list_with_total"
	herader := make(map[string]string)
	token, err := GetToken()
	if err != nil {
		log.Println(err)
		return RoomUser{}, err
	}
	herader["Authorization"] = "Bearer " + token

	resp, err := tools.PostJson(url, herader, param, "POST")
	var user RoomUser
	err = json.Unmarshal(resp, &user)
	if err != nil {
		log.Println(err)
		return user, err
	}

	return user, nil
}

type User struct {
	Msg  string `json:"msg"`
	Code int    `json:"code"`
	Data []struct {
		Uid         string  `json:"uid"`
		UserId      int     `json:"userId"`
		Nickname    string  `json:"nickname"`
		Avatar      string  `json:"avatar"`
		Area        string  `json:"area"`
		Addtime     string  `json:"addtime"`
		Phone       string  `json:"phone"`
		ThirdOpenid string  `json:"third_openid"`
		PayAmount   float64 `json:"payAmount"`
	} `json:"data"`
}

// 获取用户消费金额
func GetUserExpend(userId int) (float64, error) {

	url := "https://openapi.vzan.com/api/v2/live/get_live_user_list"
	herader := make(map[string]string)
	token, err := GetToken()
	if err != nil {
		log.Println(err)
		return 0, err
	}
	herader["Authorization"] = "Bearer " + token

	param := make(map[string]any)
	param["userId"] = userId
	resp, err := tools.PostJson(url, herader, param, "POST")
	var user User
	err = json.Unmarshal(resp, &user)
	if err != nil {
		log.Println(err)
		return 0, err
	}

	if user.Code != 0 {

		return 0, errors.New(user.Msg)
	}
	for _, v := range user.Data {
		if v.UserId == userId {
			//f, _ := strconv.ParseFloat(v.PayAmount, 64)
			return v.PayAmount, nil
		}
	}

	return 0, nil
}
